package com.rp.system.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.rp.common.utils.JsonUtil;
import com.rp.controller.RpController;
import com.rp.system.po.Module;
import com.rp.system.service.ModuleService;

@Controller
@RequestMapping("/rp/system/moduleMng/")
public class ModuleController extends RpController {

	@Autowired
	private ModuleService moduleService;
	
	@RequestMapping("showModuleGrid")
	public ModelAndView showModuleGrid(){
		
		return forward("/rp/system/moduleMng/moduleGrid.jsp");
	}
	
	@ResponseBody
	@RequestMapping("getModules")
	public List<Module> getModules(String name){
		if(pageParam.getSortField().isEmpty()){
			pageParam.setSortField("createDate");
			pageParam.setSortOrder("asc");
		}
		List<Module> modules = moduleService.getModuleDao().getModules(pageParam, name);
		return modules;
	}
	
	@ResponseBody
	@RequestMapping("selectModules")
	public List<Module> selectModules(String name){
		return moduleService.getModuleDao().getModulesByName(name);
	}
	
	@ResponseBody
	@RequestMapping("saveModules")
	public String saveModules(String data){
		try {
			List<Module> modules = JsonUtil.getMapper().readValue(data, JsonUtil.getCollectionType(ArrayList.class, Module.class));
			for (Module module : modules) {
				if(module.getId() == null){
					moduleService.addModule(module);
				}else{
					moduleService.updateModule(module);
				}
			}
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	@ResponseBody
	@RequestMapping("deleteModules")
	public String deleteModules(String data){
		List<Module> modules;
		try {
			modules = JsonUtil.jsonToList(data, "com.rp.system.po.Module");
			for (Module module : modules) {
				moduleService.deleteModule(module.getId());
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
		
		return SUCCESS;
	}
	
	@ResponseBody
	@RequestMapping("moveModules")
	public String moveModules(String[] ids, String targetId){
		try {
			moduleService.moveModules(ids, targetId);
		} catch (Exception e) {
			e.printStackTrace();
			return e.getMessage();
		}
		return SUCCESS;
	}
	
	@ResponseBody
	@RequestMapping("moveModulesToRoot")
	public String moveModulesToRoot(String[] ids){
		moduleService.moveModulesToRoot(ids);
		return SUCCESS;
	}
	
}
